<?php
namespace app\index\model;
use think\Db;
/**
 * Created by Submint Text.
 * User: hetaoren<452649510@qq.com>
 * Date: 2017/03/10
 * Explain: 商品类
 */
class Goods extends Base{
     /**
      *  商品列表
      */
	public function pageQuery(){
		$goodsName = input('goodsName');
		$where = [];
		$where['dataFlag'] = 1;
		if($goodsName != '')$where['goodsName|goodsSn'] = ['like',"%$goodsName%"];
		$page = $this->where($where)->order('goodsId desc')->paginate(input('pagesize/d'))->toArray();
		if(count($page['Rows'])>0){
			foreach ($page['Rows'] as $key => $v){
  				$page['Rows'][$key]['profit'] = $v['salePrice']-$v['costPrice'];
			}
		}
		return $page;
	}

	/**
	 * 新增
	 */
	public function add(){
		$data = input('post.');
		$data["createTime"] = date('Y-m-d H:i:s');
		$result = $this->validate('Goods.add')->allowField(true)->save($data);
        if(false !== $result){
        	return HTRReturn("新增成功", 1);
        }else{
        	return HTRReturn($this->getError());
        }
	}
    /**
	 * 编辑
	 */
	public function edit(){
		$goodsId = input('post.goodsId/d',0);
		$data = input('post.');
		HTRUnset($data, 'goodsId,createTime');
		$result = $this->validate('Goods.edit')->allowField(true)->save($data,['goodsId'=>$goodsId]);
        if(false !== $result){
        	return HTRReturn("编辑成功", 1);
        }else{
        	return HTRReturn($this->getError());
        }
	}

	/**
	 * 删除商品
	 */
	public function del(){
		$id = input('post.id/d');
		$data = [];
		$data['dataFlag'] = -1;
		Db::startTrans();
		try{
		    $result = $this->update($data,['goodsId'=>$id]);
	        if(false !== $result){
		    	$result = model('stocks')->update($data,['goodsId'=>$id]);
		    	if(false !== $result){
		        	Db::commit();
		        	return HTRReturn("删除成功", 1);
		        }
	        }
		}catch (\Exception $e) {
            Db::rollback();
            return HTRReturn('删除失败');
        }
	}
}
